package service

import (
	"fmt"
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	"gitee.com/zaiqiang231/lovesport-user-service/app/model"
	"gitee.com/zaiqiang231/lovesport-user-service/app/model/req"
	"gitee.com/zaiqiang231/lovesport-user-service/app/store"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type ServiceApi struct{}

var ServiceApiInstance = new(ServiceApi)

func (service *ServiceApi) HasData() (result bool) {
	store.GetDataStore().Api().Execute(func(db *gorm.DB) {
		var api model.SysApi
		if !errors.Is(db.First(&api).Error, gorm.ErrRecordNotFound) {
			result = true
		}
	})
	return result
}

func (service *ServiceApi) InitData(entities []model.SysApi) {
	store.GetDataStore().Api().Execute(func(db *gorm.DB) {
		err := db.Create(entities).Error
		if err != nil {
			baseLog.Errorf("ServiceApi InitData创建失败 %v", err)
		}
	})
}

func (service *ServiceApi) GetApiList(api model.SysApi, pageInfo req.PageInfo, order string, desc bool) (list interface{}, total int64, err error) {
	var apiList []model.SysApi
	store.GetDataStore().Api().Execute(func(db *gorm.DB) {
		limit := pageInfo.PageSize
		offset := pageInfo.PageSize * (pageInfo.Page - 1)
		tempdb := db.Model(&model.SysApi{})
		if api.Path != "" {
			tempdb = tempdb.Where("path LIKE ?", "%"+api.Path+"%")
		}
		if api.Description != "" {
			tempdb = tempdb.Where("description LIKE ?", "%"+api.Description+"%")
		}
		if api.Method != "" {
			tempdb = tempdb.Where("method = ?", api.Method)
		}
		if api.ApiGroup != "" {
			tempdb = tempdb.Where("api_group LIKE ?", "%"+api.ApiGroup+"%")
		}
		err = tempdb.Count(&total).Error

		if err != nil {
			return
		} else {
			tempdb = tempdb.Limit(limit).Offset(offset)
			if order != "" {
				var OrderStr string
				orderMap := make(map[string]bool, 5)
				orderMap["id"] = true
				orderMap["path"] = true
				orderMap["api_group"] = true
				orderMap["description"] = true
				orderMap["method"] = true
				if orderMap[order] {
					if desc {
						OrderStr = order + " desc"
					} else {
						OrderStr = order
					}
				} else {
					err = fmt.Errorf("非法的排序字段: %v", order)
					return
				}
				err = tempdb.Order(OrderStr).Find(&apiList).Error
			} else {
				err = tempdb.Order("api_group").Find(&apiList).Error
			}
		}

	})
	return apiList, total, err
}

func (service *ServiceApi) CreateApi(api *model.SysApi) (err error) {
	store.GetDataStore().Api().Execute(func(db *gorm.DB) {
		if !errors.Is(db.Where("path = ? AND method = ?", api.Path, api.Method).First(&model.SysApi{}).Error, gorm.ErrRecordNotFound) {
			err = errors.New("存在相同api")
			return
		}
		err = db.Create(api).Error
	})

	return err
}

func (service *ServiceApi) UpdateApi(api *model.SysApi) (err error) {
	store.GetDataStore().Api().Execute(func(db *gorm.DB) {
		var oldA model.SysApi
		err = db.Where("id = ?", api.ID).First(&oldA).Error
		if err != nil {
			return
		}
		if oldA.Path != api.Path || oldA.Method != api.Method {
			if !errors.Is(db.Where("path = ? AND method = ?", api.Path, api.Method).First(&model.SysApi{}).Error, gorm.ErrRecordNotFound) {
				err = errors.New("存在相同api路径")
				return
			}
		}
		err = db.Save(api).Error
	})
	return err
}

func (service *ServiceApi) GetApiById(id uint) (api model.SysApi, err error) {
	return store.GetDataStore().Api().Get(id)
}

func (service *ServiceApi) DeleteApiById(id uint) (err error) {
	store.GetDataStore().Api().Execute(func(db *gorm.DB) {
		var entity model.SysApi
		err = db.Where("id = ?", id).First(&entity).Error // 根据id查询api记录
		if errors.Is(err, gorm.ErrRecordNotFound) {       // api记录不存在
			return
		}
		err = db.Delete(&entity).Error
	})
	return
}

func (service *ServiceApi) DeleteApisByIds(ids req.IdsReq) (err error) {
	store.GetDataStore().Api().Execute(func(db *gorm.DB) {
		var apis []model.SysApi
		err = db.Find(&apis, "id in ?", ids.Ids).Delete(&apis).Error
		if err != nil {
			return
		}
	})
	return
}
